package cn.tnar.yunpark.huasai.nbiot;

import cn.tnar.yunpark.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 华赛NBIOT地磁车位检测器心跳消息
 * Created by tieh on 2017/6/21.
 */
public class HuasaiNbiotKeepAliveMessage extends HuasaiNbiotMessage {
    private static final Logger log = LoggerFactory.getLogger(HuasaiNbiotKeepAliveMessage.class);

    /**
     * 地磁状态 ，0-无车 1-有车
     * offset: 19, length: 4
     */
    private int status;

    /**
     * 电池电量，0-7档
     * offet: 21, length: 1
     */
    private int power;

    /**
     * 信号强度
     * offset: 26, length: 1
     */
    private byte rssi;

    /**
     * 保留位
     * offset: 27, length: 2
     */
    private short reserved;
    private String powerShow;
    private String rssiShow;

    /**
     * CRC16
     * offset: 29, length: 2
     */
    @Override
    protected int getCrcOffset() {
        return 33;
    }

    @Override
    public int getStatus() {
        return status;
    }

    @Override
    public int getPower() {
        return power;
    }

    @Override
    public int getRssi() {
        return rssi;
    }

    @Override
    protected void checkValid(byte[] data, int len) throws HuasaiException {
        super.checkValid(data, len);
        if (len != 35) {
            String error = "报文长度不等于35: " + len;
            log.warn(error);
            throw new HuasaiException(error);
        }
    }

    @Override
    protected void parse(byte[] data, int len) throws HuasaiException {
        super.parse(data, len);
        status = buf.getInt(19);
        packCount = buf.getShort(23);
        power = buf.getByte(25);
        magId = buf.getInt(26);
        rssi = buf.getByte(30);
        reserved = buf.getShort(31);
    }

    @Override
    public String toString() {
        return "地磁心跳消息{" +
                "packCount=" + packCount +
                "timestamp=" + timestamp +
                ", status=" + status +
                ", power=" + power +
                ", rssi=" + rssi +
                ", magId=" + magId +
                '}';
    }

    public String getPowerShow() {
        int vPower = power * 100;
        if(vPower < 0) {
            vPower = 0;
        } else if(vPower > 700) {
            vPower = 700;
        }
        return Integer.toString(vPower / 7);
    }

    /**
     * 0 -113dBm or less
     1 -111dBm
     2...30 -109... -53dBm
     31 -51dBm or greater
     * @return 0% ~ 100%
     */
    public String getRssiShow() {
        int scopeRssi = rssi;
        if (rssi < 0) {
            scopeRssi = 0;
        } else if (rssi > 31) {
            scopeRssi = 31;
        }
        return Integer.toString((31 - scopeRssi) * 100 / 31);
    }
}
